package com.jzr.medical.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jzr.common.BaseController;
import com.jzr.common.entity.vo.Result;
import com.jzr.common.entity.vo.ResultPage;
import com.jzr.common.util.QueryUtil;
import com.jzr.common.util.U;
import com.jzr.common.util.UrlUtil;
import com.jzr.medical.db1.dto.DeviceDto;
import com.jzr.medical.db1.service.AppVersionService;
import com.jzr.medical.db1.service.DeviceService;
import com.jzr.medical.db1.vo.AppTypeVersionVo;
import com.jzr.medical.db1.vo.AppVersionVo;
import com.jzr.medical.db1.vo.DeviceVo;
import com.jzr.netty.common.base.DeviceLive;
import com.jzr.netty.common.protocol.*;
import com.jzr.netty.common.service.AdminNettyClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/device")
public class DeviceController extends BaseController {
    @Value("${nettyServer.ip}")
    private String nettyServerIp;

    @Value("${nettyServer.port}")
    private int nettyServerPort;

    @Autowired
    AppVersionService appVersionService;

    @Value("${file.app-upload-folder}")
    private String appUploadFolder;

    @Value("${file.app-download-url}")
    private String appDownloadUrl;

    @Autowired
    private DeviceService deviceService;

    public IPage<DeviceVo> getPage(@RequestBody DeviceDto record){
        QueryWrapper<DeviceVo> qw = new QueryWrapper<>();
        QueryUtil.orderBy(qw,record.getOrderByClause());
        qw.eq(U.isNotBlank(record.getDeptCode()),DeviceVo.DeptCode_,record.getDeptCode())
                .eq(U.isNotBlank(record.getDeviceType()),DeviceVo.DeviceType_,record.getDeviceType());
        IPage<DeviceVo> page = new Page<>(record.getPageNum(),record.getPageSize());
        List<DeviceVo> list = deviceService.list(page,qw);
        page.setRecords(list);
        return page;
    }

    @PostMapping("/liveList")
    public ResultPage<DeviceVo> liveList(@RequestBody DeviceDto record){
        try {
            //所有的设备;
            IPage<DeviceVo> page = this.getPage(record);
            List<DeviceVo> allList = page.getRecords();
            if(allList == null || allList.isEmpty()){
                return ResultPage.success("没有记录",page);
            }
            List<String> deviceNoList = allList.stream().map(a->a.getDeviceNo()).collect(Collectors.toList());
            List<DeviceLive> liveList = null;
            String msg = "";
            //在线的设备
            try {
                GetDeviceListRequest request = new GetDeviceListRequest();
                request.setDeptCode(record.getDeptCode());
                request.setDeviceType(record.getDeviceType());
                request.setDeviceNoList(deviceNoList);
                try (AdminNettyClient client = new AdminNettyClient(nettyServerIp, nettyServerPort)) {
                    GetDeviceListResponse response = (GetDeviceListResponse) client.send(request);
                    if (0 == response.getStatus()) {
                        liveList = response.getList();
                    } else {
                        msg = "获取在线设备列表出错";
                    }
                }
            }catch (Exception e){
                msg = "获取在线设备列表出错,"+e.getMessage();
            }

            //LastAppVersion
            List<AppTypeVersionVo> appList = appVersionService.getLastAppCodeList();

            if(liveList != null && liveList.size() >0) {
                for (DeviceVo dv: allList) {
                    dv.setRegisterState(0);
                    //复制在线设备数据
                    for(DeviceLive live : liveList){
                        if(dv.getDeviceNo() != null && live.getDeviceNo() != null
                                && dv.getDeviceNo().equalsIgnoreCase(live.getDeviceNo())){
                            BeanUtils.copyProperties(live,dv);
                            dv.setRegisterState(1);
                        }
                    }
                    //填充LastAppVersion
                    for(AppTypeVersionVo item : appList){
                        if(dv.getDeviceType() != null && item != null && item.getSoftType() != null
                            && dv.getDeviceType().intValue() == item.getSoftType().intValue()){
                            dv.setLastAppVersion(item.getFullVersion().toString());
                        }
                    }
                }
            }else{
                for(DeviceVo dv: allList){
                    dv.setRegisterState(0);
                }
            }

            return ResultPage.success(page);
        }catch (Throwable e){
            e.printStackTrace();
            return ResultPage.fail("获取列表失败,"+e.getMessage());
        }
    }

    @PostMapping("/upgrade")
    public Result<UpgradeResponse> upgrade(String deptCode, Integer deviceType, String deviceIp){
        if(deviceType == null){
            return Result.fail("请指定deviceType");
        }
        AppVersionVo appVersion = this.getLastApp(deviceType);
        if(appVersion == null){
            return Result.fail("不存在该类型的app");
        }

        try {
            UpgradeDeptRequest request = new UpgradeDeptRequest();
            request.setDeptCode(deptCode);
            request.setDeviceIp(deviceIp);
            request.setDeviceType(deviceType);
            request.setAppUrl(appVersion.getAccessUrl());
            request.setAppVersion(appVersion.getFullVersion());
            request.setUpgradeMode(2);
            try(AdminNettyClient client = new AdminNettyClient(nettyServerIp, nettyServerPort)) {
                UpgradeResponse response = (UpgradeResponse) client.send(request);
                return Result.success("成功", response);
            }
        }catch (Throwable e){
            return Result.fail("发送升级指令失败,"+e.getMessage());
        }

    }

    @PostMapping("/reloadData")
    public Result<ReloadDataResponse> reloadData(String deptCode, Integer deviceType, String deviceIp){
        try {
            ReloadDataDeptRequest request = new ReloadDataDeptRequest();
            request.setDeptCode(deptCode);
            request.setDeviceIp(deviceIp);
            request.setDeviceType(deviceType);
            try(AdminNettyClient client = new AdminNettyClient(nettyServerIp, nettyServerPort)) {
                ReloadDataResponse response = (ReloadDataResponse) client.send(request);
                return Result.success("成功", response);
            }
        }catch (Throwable e){
            return Result.fail("发送重载数据指令失败,"+e.getMessage());
        }
    }

    @PostMapping("/restartApp")
    public Result<RestartAppResponse> restartApp(String deptCode, Integer deviceType, String deviceIp){
        try {
            RestartAppDeptRequest request = new RestartAppDeptRequest();
            request.setDeptCode(deptCode);
            request.setDeviceIp(deviceIp);
            request.setDeviceType(deviceType);
            try(AdminNettyClient client = new AdminNettyClient(nettyServerIp, nettyServerPort)) {
                RestartAppResponse response = (RestartAppResponse) client.send(request);
                return Result.success("成功", response);
            }
        }catch (Throwable e){
            return Result.fail("发送重启设备指令失败,"+e.getMessage());
        }
    }

    @PostMapping("/restartDevice")
    public Result<RestartDeviceResponse> restartDevice(String deptCode,Integer deviceType, String deviceIp){
        try {
            RestartDeviceDeptRequest request = new RestartDeviceDeptRequest();
            request.setDeptCode(deptCode);
            request.setDeviceIp(deviceIp);
            request.setDeviceType(deviceType);
            try(AdminNettyClient client = new AdminNettyClient(nettyServerIp, nettyServerPort)) {
                RestartDeviceResponse response = (RestartDeviceResponse) client.send(request);
                return Result.success("成功", response);
            }
        }catch (Throwable e){
            return Result.fail("发送重启设备指令失败,"+e.getMessage());
        }
    }

    @PostMapping("/lockScreen")
    public Result<LockScreenResponse> lockScreen(String deptCode,Integer deviceType, String deviceIp){
        try {
            LockScreenDeptRequest request = new LockScreenDeptRequest();
            request.setDeptCode(deptCode);
            request.setDeviceIp(deviceIp);
            request.setDeviceType(deviceType);
            try(AdminNettyClient client = new AdminNettyClient(nettyServerIp, nettyServerPort)) {
                LockScreenResponse response = (LockScreenResponse) client.send(request);
                return Result.success("成功", response);
            }
        }catch (Throwable e){
            return Result.fail("发送锁屏指令失败,"+e.getMessage());
        }
    }

    private AppVersionVo getLastApp(Integer softType){
        if(softType == null){
            return null;
        }
        AppVersionVo AppVersionVo = appVersionService.lastVersion(softType);
        if(AppVersionVo == null){
            return null;
        }
        String softName = AppVersionVo.getSoftName() == null ? "" : AppVersionVo.getSoftName();

        AppVersionVo.setAccessUrl(UrlUtil.concat(appDownloadUrl, softName));

        return AppVersionVo;
    }
}
